
package org.springblade.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.CommonConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Param;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.mapper.UserMapper;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IParamService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.UserVO;
import org.springframework.stereotype.Service;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements IUserService {
	private IParamService paramService;
	private IDeptService deptService;

	@Override
	public boolean submit(User user) {
		if (Func.isNotEmpty(user.getPassword())) {
			user.setPassword(DigestUtil.encrypt(user.getPassword()));
		}
		Integer cnt = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, user.getTenantId()).eq(User::getAccount, user.getAccount()));
		if (cnt > 0) {
			throw new ApiException("当前用户已存在!");
		}
		return saveOrUpdate(user);
	}

	@Override
	public IPage<User> list(IPage<User> page,User user){
		LambdaQueryWrapper<User> wrappres = Wrappers.<User>query().lambda();
		if(StringUtils.isNotEmpty(user.getDeptId())){
			wrappres.eq(User::getDeptId,user.getDeptId());
		}
		if(StringUtils.isNotEmpty(user.getAccount())){
			wrappres.like(User::getAccount,"%" + user.getAccount() + "%");
		}
		if(StringUtils.isNotEmpty(user.getRealName())){
			wrappres.like(User::getRealName,"%" + user.getRealName() + "%");
		}
		wrappres.notIn(User::getAccount,CommonConstant.SYSTEM_MANAGER);
		return page(page, wrappres);
	}

	@Override
	public IPage<User> selectUserPage(IPage<User> page, User user) {
		return page.setRecords(baseMapper.selectUserPage(page, user));
	}

	@Override
	public UserInfo userInfo(Long userId) {
		UserInfo userInfo = new UserInfo();
		User user = baseMapper.selectById(userId);
		userInfo.setUser(user);
		if (Func.isNotEmpty(user)) {
			List<String> roleAlias = baseMapper.getRoleAlias(Func.toStrArray(user.getRoleId()));
			userInfo.setRoles(roleAlias);
		}
		return userInfo;
	}

	@Override
	public UserInfo userInfo(String tenantId, String account, String password) {
		UserInfo userInfo = new UserInfo();
		User user = baseMapper.getUser(tenantId, account, password);
		// 查询参数表初始化密码
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("paramKey","account.initPassword");
		Param detail = paramService.getOne(Condition.getQueryWrapper(param, Param.class));
		String pwd = DigestUtil.encrypt(detail.getParamValue());
		// 判断输入的密码是否与初始化密码一致，如果一直则强制修改密码
		if(user != null && pwd.equals(user.getPassword()) ){
			userInfo.setIsUpdPwd(1);
		} else {
			userInfo.setIsUpdPwd(0);
		}
		userInfo.setUser(user);
		if (Func.isNotEmpty(user)) {
			List<String> roleAlias = baseMapper.getRoleAlias(Func.toStrArray(user.getRoleId()));
			userInfo.setRoles(roleAlias);
		}
		return userInfo;
	}

	@Override
	public boolean grant(String userIds, String roleIds) {
		User user = new User();
		user.setRoleId(roleIds);
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toIntList(userIds)));
	}

	@Override
	public boolean resetPassword(String userIds) {
		User user = new User();
		// 查询参数表初始化密码
		Map<String, Object> param = new HashMap<>();
		param.put("paramKey","account.initPassword");
		Param detail = paramService.getOne(Condition.getQueryWrapper(param, Param.class));
		String initPwd = "";
		if(detail != null && StringUtils.isNotEmpty(detail.getParamValue())){
			initPwd = detail.getParamValue();
		} else {
			initPwd = CommonConstant.DEFAULT_PASSWORD;
		}
		user.setPassword(DigestUtil.encrypt(initPwd));
		user.setUpdateTime(DateUtil.now());
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toIntList(userIds)));
	}

	@Override
	public boolean updatePassword(BladeUser bladeUser, String oldPassword, String newPassword, String newPassword1,String account) {
		User user;
		if(bladeUser != null){
			user = getById(bladeUser.getUserId());
		} else {
			//登录前强制修改初始密码
			user = this.getOne(Wrappers.<User>query().lambda().eq(User::getAccount, account));
		}
		if (!newPassword.equals(newPassword1)) {
			throw new ServiceException("请输入正确的确认密码!");
		}
		if (!user.getPassword().equals(DigestUtil.encrypt(oldPassword))) {
			throw new ServiceException("原密码不正确!");
		}
		return this.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.encrypt(newPassword)).eq(User::getId, user.getId()));
	}

	@Override
	public List<String> getRoleName(String roleIds) {
		return baseMapper.getRoleName(Func.toStrArray(roleIds));
	}

	@Override
	public List<String> getDeptName(String deptIds) {
		return baseMapper.getDeptName(Func.toStrArray(deptIds));
	}

}
